package com.darrenchan.spark.javaapi;

import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.SparkSession;
import scala.Tuple2;

import java.util.Arrays;

/**
 * 文件内容：
 * hello spark
 * hello hadoop
 * hello flink
 * hello storm
 */
public class WordCountApp {
    public static void main(String[] args) {
        //这是另外一种写法（不用sparkconf和sparkcontext）
        SparkSession spark = SparkSession.builder().master("local[2]").appName("WordCountApp").getOrCreate();

        //业务逻辑
        JavaRDD<String> lines = spark.read().textFile("D:\\hello.txt").javaRDD();

        JavaRDD<String> words = lines.flatMap(line -> Arrays.asList(line.split(" ")).iterator());

        JavaPairRDD<String, Integer> counts =
                words.mapToPair(word -> new Tuple2<>(word, 1)).reduceByKey((a, b) -> a + b);

        System.out.println(counts.collect());


        spark.stop();
    }
}
